package com.shh.rabbitmq.service;

import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.shh.rabbitmq.dao.OrderDao;
import com.shh.rabbitmq.domain.OrderDO;
/**
 * 订单队列异常，死信对了
 * @author shaoh
 *
 */
@Service
public class OrderDeadHandleService{
	
	@Autowired
	private OrderDao orderDao;
	
    @RabbitHandler
    @RabbitListener(queues = {"dead.order.queue"})
    public void reviceMessage(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
    	String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), "UTF-8");
        System.out.println("私信队列重试-----》派单服务平台" + msg + ",消息id:" + messageId);
        OrderDO orderDO = JSONObject.parseObject(msg,OrderDO.class);
        if (StringUtils.isEmpty(orderDO.getOrderNo())) {
            return;
        }
        try {
            //插入派单服务订单表
            orderDao.addOrder(orderDO);
            //手动签收消息,通知mq服务器端删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //死信队列重试失败，需要人工干预
        	/**
        	 * 1.冗余存库
        	 * 2.人工介入
        	 * 3.发送消息、短信
        	 */
        	System.out.println("私信队列重试-----》派单服务平台" + msg + ",重试结果:死信队列重试失败，需要人工干预 ");
        }
    }
}

